﻿using System;
using System.IO;
using System.Net.Sockets;
using System.Runtime.Serialization;
using AuctionClassLibrary;
using System.Runtime.Serialization.Formatters.Binary;

namespace Laks
{
    [Serializable]
    class ClientThread
    {
        public AuctionReceiveDelegate AuctionReceiveEvent;
        public GotBidDelegate GotBidEvent;
        public HammerDelegate HammerEvent;
        public CountClientsDelegate CountClientsEvent;
        public bool CloseAuction { get; set; }
        public string LastPrice;

        public void HandleAuction(NetworkStream _networkStream, StreamReader _streamReader, StreamWriter _streamWriter)
        {
            Auction auction;
            string[] msg;
            string command;
            BinaryFormatter bf;

            try
            {
                bf = new BinaryFormatter();
                auction = (Auction)bf.Deserialize(_networkStream);
                LastPrice = _streamReader.ReadLine();
                AuctionReceiveEvent(auction, LastPrice);

                while (true) //receive bids
                {
                    string data = _streamReader.ReadLine(); // Read obj from streamreader
                    if (data == null)
                        break;
                    if (data == "sold")
                    {
                        auction = (Auction)bf.Deserialize(_networkStream);
                        LastPrice = _streamReader.ReadLine();
                        AuctionReceiveEvent(auction, LastPrice);
                    }
                    else
                    {
                        msg = data.Split(';');
                        command = msg[msg.Length - 1].Trim().ToLower();
                        switch (command)
                        {
                            case "bid":
                                GotBidEvent(DateTime.Now, msg[0], msg[1]);
                                break;
                            case "hammer":
                                HammerEvent(DateTime.Now, msg[0]);
                                break;
                            case "hammer3":
                                CloseAuction = true;
                                HammerEvent(DateTime.Now, msg[0]);
                                break;
                            case "count":
                                CountClientsEvent(msg[0]);
                                break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (e is SerializationException || e is NullReferenceException) { }
            }
        }
    }
}